layui.extend({
    handle: "{/}/static/admin/form/js/handle",
}).define(['handle'], function (exports) {
    var a = layui.jquery,
        f = layui.form,
        ly = layui.layer,
        L = layui.laydate,
        t = layui.table,
        H = layui.handle,
        tt = 'table',
        tid = 'form_table',
        u = layui.util,
        upload = layui.upload,
        uploads_url = a("#uploads_url").val(),
        admin_map = a("#admin_map").val(),
        Lc = a('.layui-card-body'),
        T = {
            init: function () {
                //表单验证
                f.verify();

                //搜索表单提交
                f.on('submit(search)', function (data) {
                    t.reload('form_table', {where: f.val("search-form"), page: {curr: 1}});
                    a(".resetSearch").show();
                    return false;
                });
                //重置搜索表单
                f.on('submit(resetSearch)', function (data) {
                    a(".search-form")[0].reset();
                    t.reload('form_table', {where: f.val("search-form"), page: {curr: 1}});
                    a(".resetSearch").hide();
                    return false;
                });

                //触发排序事件
                t.on('sort(table)', function (obj) {
                    t.reload('form_table', {
                        initSort: obj,
                        where: {tableSortField: obj.field, tableSortOrder: obj.type, tableSearch: f.val("search-form")}
                    });
                });

                //表格开关状态栏监听
                f.on('switch(status)', function (obj) {
                    const values = obj.elem.attributes[5].value.split('|'),
                        data = {
                            id: this.value,
                            key: obj.elem.attributes[1].value,
                            val: obj.elem.checked ? values[0] : values[1],
                            url: a("#update_url").val()
                        }
                    T.method.save(data);
                });

                //兼容手动渲染表格开关状态栏监听
                f.on('switch(switch_old)', function (obj) {
                    a.get(a(this).attr('url'), {val: a(this).prop('checked')})
                })

                //监听统一提交
                f.on('submit(save)', function () {
                    T.method.load();
                    const btn = a(this), fo = a(a(this).attr('formObj')), back_url = btn.attr('data-back-url');
                    btn.attr('disabled', true);
                    a.post(fo.attr('action'), fo.serialize(), function (data) {
                        ly.closeAll();
                        if (data.code === 1) {
                            notify.success(data.msg, 1000, function () {
                                if (back_url) {
                                    location.href = back_url;
                                } else {
                                    parent.layer.closeAll();
                                    if (parent.$(".layui-table-page").length > 0) {
                                        parent.layui.table.reload('form_table', {
                                            page: {
                                                curr: parent.$(".layui-laypage-em").next().text()
                                            },
                                        });
                                    } else {
                                        var w = window.frames.frameElement.id.includes('layui-layer-iframe');
                                        w ? parent.location.reload() : location.reload();
                                    }
                                }
                            });

                        } else {
                            notify.error(data.msg);
                            btn.removeAttr('disabled');
                        }
                    });

                    return false;
                });
                //监听图片上传
                upload.render({
                    elem: '.uploadImage',
                    url: uploads_url,
                    before: function (obj) {
                        layer.load();
                        var showImage = this.item.find('.showImage');
                        obj.preview(function (index, file, result) {
                            showImage.attr('src', result)
                        });
                    },
                    done: function (data) {
                        ly.closeAll();
                        if (data.code === 200) {
                            this.item.find('.inpImage').val(data.data.url);
                            notify.success(data.msg);
                        } else {
                            notify.error(data.msg);
                        }
                    },
                    error: function () {
                        ly.closeAll();
                    }
                });
                //其他jquery监听事件
                Lc.on('click', '.openShowImg', function () {
                    //图片预览
                    const value = a(this).attr("data-value").split(','), data = [];
                    for (i in value) {
                        data.push({src: value[i]});
                    }
                    ly.photos({photos: {"data": data, "start": 0}, anim: 5, closeBtn: 1});

                }).on('click', '.openEditor', function () {
                    //预览Editor
                    var value = a(this).attr("data-value");
                    ly.open({
                        type: 1,
                        area: ['800px', '80%'],
                        shade: 0.4,
                        shadeClose: true,
                        anim: 2,
                        title: '预览',
                        content: '<div style="padding: 10px">' + value + '</div>'
                    });
                }).on('click', '.openVideo', function () {
                    //预览音频
                    var value = $(this).attr("data-value");
                    ly.open({
                        type: 1,
                        area: ['40%', '45%'],
                        shade: 1,
                        shadeClose: true,
                        anim: 2,
                        title: false,
                        content: '<video src='+value+'></video>'
                    });
                }).on('change', '.tableInput', function () {
                    //表格input改变事件
                    const obj = a(this), data = {
                        id: obj.attr('data-id'),
                        key: obj.attr('data-key'),
                        val: obj.val(),
                        url: obj.attr('data-url')
                    };
                    T.method.save(data);
                })
                //监听手动渲染表格全选事件
                f.on('checkbox(list_all)', function (obj) {
                    var checked = obj.elem.checked;
                    a("[lay-filter=list_checkbox]").prop("checked", checked);
                    f.render('checkbox');
                })

                //监听搜索表单回车提交
                a(".nav_search input").keydown(function (e) {
                    if (e.keyCode === 13) {
                        t.reload('form_table', {where: f.val("search-form"), page: {curr: 1}});
                        a(".resetSearch").show();
                        e.preventDefault();
                        return false;
                    }
                })

                a(".search_open").click(function () {
                    if (a(this).text() == '展开') {
                        a(".hidden").removeClass('layui-hide');
                        a(this).text('收起').addClass('search_close').removeClass('search_open');
                    } else {
                        a(".hidden").addClass('layui-hide');
                        a(this).text('展开').addClass('search_open').removeClass('search_close');
                    }
                });

                // 单独菜单展开
                a('.x-show').click(function () {
                    var cateId;
                    if (a(this).attr('status') == 'true') {
                        a(this).html('&#xe625;');
                        a(this).attr('status', 'false');
                        cateId = a(this).parents('tr').attr('cate-id');
                        a("tbody tr[fid=" + cateId + "]").show();
                    } else {

                        a(this).html('&#xe623;');
                        a(this).attr('status', 'true');
                        cateId = a(this).parents('tr').attr('cate-id');
                        cateIds = [];
                        T.method.getCateId(cateId);

                        for (var i in cateIds) {
                            a("tbody tr[cate-id=" + cateIds[i] + "]").hide().find('.x-show').html('&#xe623;').attr('status', 'true');
                        }
                    }
                })


                a(".layui-badge-search").click(function () {
                    var url = a(this).attr('data-url');
                    if (url) {
                        location.href = url;
                    } else {
                        a(this).parents('.layui-badge-parent').find('.layui-badge-hidden').val(a(this).attr('data-val'))
                        t.reload(tid, {
                            where: f.val("search-badge-form")
                            , page: {
                                curr: 1
                            },
                        });
                        a(this).addClass('active').siblings().removeClass('active')
                    }

                });

                a('.up-down').click(function () {

                    if (a(this).hasClass('up')) {
                        a(this).html('展开<i class="layui-icon layui-nav-more layui-icon-down"></i>').removeClass('up');
                        a('.search_list').hide();
                    } else {
                        a(this).html('收起<i class="layui-icon layui-nav-more layui-icon-up"></i>').addClass('up');
                        a('.search_list').show();
                    }
                });


                //监听表格右侧按钮监听事件
                t.on('tool(' + tt + ')', function (obj) {
                    try {
                        T.handleTool(obj);
                    } catch (e) {
                        alert('发生错误了');
                    }
                });
                //监听顶部按钮事件
                u.on('lay-event', {
                    //顶部统一操作
                    topBtnEvent: function (that) {
                        var json = JSON.parse(that.attr('data-json'));
                        if (a.isFunction(T.method[json.event])) {
                            return T.method[json.event](json);
                        } else {
                            if (a.isFunction(H.method.top[json.event])) {
                                return H.method.top[json.event](json);
                            } else {
                                notify.error('handle.js中未定义【' + json.event + '】方法，请先定义后再调用！');
                            }
                        }
                    },
                    //顶部导出按钮操作
                    exportExcel: function (that) {
                        T.method.load()
                        a.get(that.attr('data-url'), f.val("search-form"), function (res) {
                            var timeStart = Date.now()
                            if (res.title) {
                                t.exportFile(res.title, res.data, {
                                    type: 'csv', // 导出格式
                                    title: that.attr('data-title')
                                });
                            } else {
                                t.exportFile('form_table', res.data, {
                                    type: 'csv', // 导出格式
                                    title: that.attr('data-title')
                                });
                            }
                            var spent = (Date.now() - timeStart) / 1000
                            ly.closeAll();
                            notify.success('已导出，耗时 ' + spent + ' s');
                        });
                    },
                });

            },
            method: {
                getCateId: function (cateId) {
                    a("tbody tr[fid=" + cateId + "]").each(function (index, el) {
                        var id = a(el).attr('cate-id');
                        cateIds.push(id);
                        T.method.getCateId(id);
                    });
                },

                goBack: function (url, title) {
                    parent.layui.admin.events.closeThisTabs();
                    top.layui.index.openTabsPage(url, title)
                },
                //统一加载中
                load: function layerLoad(text = '加载中....') {
                    ly.msg('<div><i class="layui-icon layui-icon-loading-1 layui-anim layui-anim-rotate layui-anim-loop"></i> ' + text + '', {
                        shade: 0.8,
                        time: 99999
                    });
                },
                //获取表格选中的id
                getCheckTableIds: function () {
                    var all = t.checkStatus(tid), ids = [];
                    if (all.length <= 0) return false;

                    all.data.forEach(function (v, i) {
                        ids.push(v.id);
                    });

                    return ids;
                },
                //顶部按钮添加操作
                add: function (json) {
                    if (json.width) {
                        T.od(json.unity_title, json.url + '&tableUniqueTitle=' + json.unity_title + '&openShowType=1', json.width, 'l');
                    } else {
                        location.href = json.url + "&back=" + json.back_url + '&tableUniqueTitle=' + json.unity_title
                    }
                },
                //顶部按钮批量Prompt操作
                _batchPrompt: function (json) {
                    var ids = T.method.getCheckTableIds();
                    if (ids.length < 1) {
                        notify.warning("请选择要操作的数据");
                        return false;
                    }
                    ly.prompt({
                        title: '正在进行<span style="color: red">《' + json.title + '》</span>操作',
                        formType: 3,
                        placeholder: json.placeholder,
                    }, function (pass, index) {
                        ly.close(index);
                        T.method.load();
                        a.post(json.url, {ids: ids, pass: pass}, function (data) {
                            ly.closeAll();
                            if (data.code === 1) {
                                notify.success(data.message ? data.message : data.msg, 1500, function () {
                                    location.reload();
                                });
                            } else {
                                notify.error(data.message ? data.message : data.msg);
                            }
                        });
                    });

                },
                //顶部按钮批量提交操作
                _batchSubmit: function (json) {
                    var ids = T.method.getCheckTableIds();
                    if (ids.length < 1) {
                        notify.warning("请选择要操作的数据");
                        return false;
                    }
                    ly.confirm('正在进行<span style="color: red">《' + json.title + '》</span>操作<br/>确定要执行吗？'
                        , {title: '请确认'}
                        , function (index) {
                            ly.close(index);
                            T.method.load();
                            a.post(json.url, {ids: ids}, function (data) {
                                ly.closeAll();
                                if (data.code === 1) {
                                    notify.success(data.message ? data.message : data.msg, 1500, function () {
                                        location.reload();
                                    });
                                } else {
                                    notify.error(data.message ? data.message : data.msg);
                                }
                            });

                        });
                },
                //顶部按钮单独提交操作
                _submitTop: function (json) {
                    ly.confirm('正在进行<span style="color: red">《' + that.text() + '》</span>操作<br/>确定要执行吗？', {title: '请确认'}, function (index) {
                        ly.close(index);
                        T.method.load();
                        a.post(json.url, function (data) {
                            ly.closeAll();
                            if (data.code === 1) {
                                notify.success(data.message ? data.message : data.msg, 1500, function () {
                                    location.reload();
                                });
                            } else {
                                notify.error(data.message ? data.message : data.msg);
                            }
                        });
                    });
                },
                //顶部按钮批量删除操作
                deleteAll: function (that, type = 1) {
                    var json = JSON.parse(that.attr('data-json')), ids = type === 2 ? tableCheck.getData() : getIds();
                    if (!ids) {
                        notify.warning("请选择要删除的数据");
                        return false;
                    }
                    ly.confirm('确定要删除所选数据吗？', {title: '请确认'}, function (index) {
                        T.method.load();
                        a.post(json.url, {id: data.id, tableUniqueTitle: tool.unity_title}, function (data) {
                            if (data.code === 1) {
                                notify.success("操作成功", 1500, function () {
                                    location.reload();
                                });
                            } else {
                                notify.error(data.msg);
                            }
                        })
                    });
                },
                _openNewPage: function (data, tool) {
                    var url = (tool.url.indexOf('?') !== -1 ? tool.url + '&' : tool.url + '?') + 'id=' + data.id + "&back=" + tool.back_url
                    var title = data.title, t = title ? tool.title + '【📌' + title + '】' : tool.title;

                    if (tool.width) {
                        var site = tool.site ? tool.site : 'l'
                        openDrawer(t, url + '&openShowType=1', tool.width, site);
                    } else {
                        location.href = url + "&tableUniqueTitle=" + tool.title
                    }
                },
                _openDrawer: function (json) {
                    if (json.width) {
                        openDrawer(json.title, json.url, json.width, 'l');
                    } else {
                        top.layui.index.openTabsPage(json.url, json.title)
                    }
                },
                //右侧按钮单独提交操作
                _submit: function (data, tool) {
                    ly.confirm('确定要' + tool.title + '吗？', {title: '请确认'}, function (index) {
                        ly.close(index);
                        T.method.load();
                        a.post(json.url, data, function (data) {
                            ly.closeAll();
                            if (data.code === 1) {
                                notify.success(data.msg, 1000, function () {
                                    location.reload();
                                });
                            } else {
                                notify.error(data.message ? data.message : data.msg);
                            }
                        });
                    });
                },
                //右侧按钮删除操作
                delete: function (data, tool, obj) {
                    ly.confirm('确定要删除吗？', {title: '请确认'}, function (index) {
                        T.method.load();
                        a.post(tool.url, {id: data.id, tableUniqueTitle: tool.unity_title}, function (data) {
                            ly.closeAll()
                            if (data.code === 1) {
                                notify.success(data.msg);
                                obj.del();
                            } else {
                                notify.error(data.msg);
                            }
                        })
                    });
                },
                //右侧按钮编辑操作
                edit: function (data, tool) {
                    var url = '', title = data.title,
                        t = title ? tool.unity_title + '【📌' + title + '】' : tool.unity_title;
                    if (tool.width) {
                        url = tool.url + '&id=' + data.id + '&uid=' + data.uid + '&tableUniqueTitle=' + tool.unity_title;
                        T.od(t, url + '&openShowType=1', tool.width, 'r');
                    } else {
                        url = tool.url + '&id=' + data.id + '&uid=' + data.uid + "&back=" + tool.back_url + '&tableUniqueTitle=' + tool.unity_title
                        location.href = url
                    }
                },
                save: function (data) {
                    data.tableUniqueStr = a("#tableUniqueStr").val();
                    data.tableUniqueTitle = a("#tableUniqueTitle").val();
                    a.post(data.url, data, function (data) {
                        if (data.code !== 1) {
                            notify.error(data.msg);
                        }
                    });
                },
            },
            //右侧按钮，自定义操作定义，引入自定义方法
            handleTool: function (obj) {
                const tool = JSON.parse(obj.event);
                if (a.isFunction(T.method[tool.event])) {
                    return T.method[tool.event](obj.data, tool, obj);
                } else {
                    if (a.isFunction(H.method.right[tool.event])) {
                        return H.method.right[tool.event](obj.data, tool, obj);
                    } else {
                        notify.error('handle.js中未定义【' + tool.event + '】方法，请先定义后再调用！');
                    }
                }
            },
            //打开新抽屉
            od: function (title, url, w, offset, h = '') {
                var anim, height = h ? h : '100%'
                switch (offset) {
                    case "r":
                        anim = 'slideLeft';
                        break;
                    case "l":
                        anim = 'slideRight';
                        break;
                    case "b":
                        anim = 'slideUp';
                        break;
                    case "t":
                        anim = 'slideDown';
                        break;
                }
                ly.open({
                    type: 2,
                    offset: offset,
                    anim: anim,
                    area: [w, height],
                    shade: 0.3,
                    shadeClose: true,
                    id: 'ID-demo-layer-direction-r',
                    title: [title, 'font-size:14px;color:#000;text-align: left;font-weight: bold'],
                    content: url,
                    success: function () {
                        a('.layui-layer-setwin').find('.layui-icon').removeClass('layui-icon-close').addClass('layui-icon-error')
                    }
                });
            },


        }


    exports('listen', T);
});